package com.lagou.edu.factory;

import com.lagou.edu.pojo.Account;
import com.lagou.edu.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    private   TransactionManager transactionManager;
    public ProxyFactory(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }






    public  Object getJDKProxy(Object target){

         Object proxyObj= Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler(){

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object ret = null;
                try {
                    transactionManager.beginTransaction();
                    ret = method.invoke(target, args);
                    transactionManager.commit();
                }catch (Exception e){
                    transactionManager.rollback();
                    throw  new Exception();
                }
                return ret;
            }
        });
         return proxyObj;
    }
}
